package com.study.kt._04project.game_tank.model

import com.study.kt._04project.game_tank.Config
import com.study.kt._04project.game_tank.business.Attachable
import com.study.kt._04project.game_tank.business.AutoMoveable
import com.study.kt._04project.game_tank.business.Destoryable
import com.study.kt._04project.game_tank.business.Sufferable
import com.study.kt._04project.game_tank.enums.Direction
import com.study.kt._04project.game_tank.ext.checkCollision
import org.itheima.kotlin.game.core.Painter


/**
 * 子弹的坐标除了可以使用构造传值，比较好的做法是在构造函数中使用闭包, 好处是坐标的数据不用在外界计算
 * 闭包中返回子弹的x、y坐标使用元组数据接收
 */
class Bullet(
    override var owner: View,
    override val currentDirection: Direction,
    create: (width: Int, height: Int) -> Pair<Int, Int>
) :
    AutoMoveable, Destoryable, Attachable {

    //默认有1点攻击力
    override val attachPower: Int = 1
    override val speed: Int = 8

    //宽高信息需要根据子弹的方向获取
    override val width: Int
    override val height: Int

    override var x: Int = 0
    override var y: Int = 0

    var isCollision = false

    private val imagePath = when (currentDirection) {
        Direction.UP -> "img/bullet_u.gif"
        Direction.DOWN -> "img/bullet_d.gif"
        Direction.LEFT -> "img/bullet_l.gif"
        Direction.RIGHT -> "img/bullet_r.gif"
    }

    init {
        val size = Painter.size(imagePath)
        width = size[0]
        height = size[1]
        val pos = create(width, height)
        x = pos.first
        y = pos.second
    }

    override fun draw() {
        Painter.drawImage(imagePath, x, y)
    }

    //根据方向 改变自己的x、y值
    override fun autoMove() {
        when (currentDirection) {
            Direction.UP -> y -= speed
            Direction.DOWN -> y += speed
            Direction.LEFT -> x -= speed
            Direction.RIGHT -> x += speed
        }
    }

    //如果子弹移动到屏幕外则可以被回收
    override fun isDestory(): Boolean {

        //如果是碰到墙，直接返回true，表示要被回收
        if (isCollision) {
            return true
        }

        if (x < -width) return true
        if (x > Config.gameWidth) return true
        if (y < -height) return true
        if (y > Config.gameHeight) return true
        return false
    }


    //检测是否碰撞到(检测是否碰撞在很多View中都会出现，例如坦克碰撞到墙，所以可以提取到父类中实现)
    override fun isCollision(sufferable: Sufferable): Boolean {
        //调用父类View的重载方法
        return checkCollision(sufferable)
    }

    override fun notifyAttach(sufferable: Sufferable) {
        //子弹碰撞物体之后需要消失
        isCollision = true
    }

}